//
//  WXApplicationModule.m
//  XYLib
//
//  Created by Richard on 2019/1/15.
//  Copyright © 2019年 XY. All rights reserved.
//

#import "WXApplicationModule.h"
#import <AdSupport/AdSupport.h>
#import <JWT/JWT.h>
#import "JWTAlgorithmFactory.h"
#import <MapKit/MapKit.h>
//#import <TencentOpenAPI/QQApiInterface.h>
//#import <TencentOpenAPI/QQApiInterfaceObject.h>
#import "UIColor+IGColor.h"

BOOL disableStatusBar = NO;
static UIView *splashView = nil;

@implementation WXApplicationModule
@synthesize weexInstance;

WX_EXPORT_METHOD(@selector(openURL:))
WX_EXPORT_METHOD_SYNC(@selector(canOpenURL:))
WX_EXPORT_METHOD(@selector(makeCall:))
WX_EXPORT_METHOD(@selector(forceToOrientation:))
WX_EXPORT_METHOD_SYNC(@selector(setStatusBarStyle:))
WX_EXPORT_METHOD_SYNC(@selector(statusBarStyle))
WX_EXPORT_METHOD(@selector(setStatusBarColor:))
WX_EXPORT_METHOD(@selector(showStatusBar:))
WX_EXPORT_METHOD_SYNC(@selector(channelName))
WX_EXPORT_METHOD_SYNC(@selector(bundleVersion))
WX_EXPORT_METHOD_SYNC(@selector(bundleId))
WX_EXPORT_METHOD_SYNC(@selector(deviceId))
WX_EXPORT_METHOD(@selector(openAppSetting))
WX_EXPORT_METHOD(@selector(openAppOSSetting))
WX_EXPORT_METHOD_SYNC(@selector(notificationSettingTypes))
WX_EXPORT_METHOD_SYNC(@selector(copyPasteboard:))
WX_EXPORT_METHOD_SYNC(@selector(JWTCode:))
WX_EXPORT_METHOD_SYNC(@selector(appStoreVersion:))
WX_EXPORT_METHOD_SYNC(@selector(getNetWorkStatus))

WX_EXPORT_METHOD_SYNC(@selector(openRatingReview))
WX_EXPORT_METHOD(@selector(openEmail:))
WX_EXPORT_METHOD(@selector(openMap:title:))
WX_EXPORT_METHOD(@selector(openQQ:))

WX_EXPORT_METHOD(@selector(getCameraPermission:))
WX_EXPORT_METHOD(@selector(isCheckCameraPermission:))
WX_EXPORT_METHOD_SYNC(@selector(setAudioPlayMode:))

-(NSDictionary *)getNetWorkStatus{
    return [[NSUserDefaults standardUserDefaults] objectForKey:@"netWorkStatus"];
}

-(void)exitApp:(int)code{
    exit(code);
}

-(NSString*)channelName{
    return @"iOS";
}

-(BOOL)canOpenURL:(NSString*)url{
    __block BOOL canopen = false;
    if (url && url.length>0) {
        dispatch_sync(dispatch_get_main_queue(), ^{
            canopen = [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:url]];
        });
    }
    return canopen;
}

-(void)openURL:(NSString*)url{
    if (url && url.length>0) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
        });
    }
}

-(void)makeCall:(NSString*)tel
{
    if (tel && tel.length>1) {
        NSString*str=[[NSString alloc] initWithFormat:@"tel://%@",[tel stringByReplacingOccurrencesOfString:@" " withString:@""]];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
    }
}

- (void)forceToOrientation:(NSInteger)iOrientation
{
    UIDeviceOrientation orientation =(UIDeviceOrientation)iOrientation;
    NSNumber *orientationUnknown = [NSNumber numberWithInt:0];
    [[UIDevice currentDevice] setValue:orientationUnknown forKey:@"orientation"];
    
    NSNumber *orientationTarget = [NSNumber numberWithInt:orientation];
    [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
}

-(void)setStatusBarStyle:(int)statusBarStyle
{
    if (NO == disableStatusBar) {
        __block NSInteger temp = statusBarStyle;
        dispatch_async(dispatch_get_main_queue(), ^{
            if (temp <= 3) {
                [[UIApplication sharedApplication] setStatusBarStyle:temp animated:NO];
            }
            else{
                [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
            }
        });
    }
}

-(NSInteger)statusBarStyle{
    return [[UIApplication sharedApplication] statusBarStyle];
}

- (void)setStatusBarColor:(NSString *)colorStr {
    if (colorStr == nil || colorStr == NULL || ![colorStr hasPrefix:@"#"]) {
        return ;
    }
    UIColor*color =  [UIColor colorWithStr:colorStr];
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
        statusBar.backgroundColor = color;
    }
}

- (void)showStatusBar:(BOOL)show
{
    if (show) {
        [[UIApplication sharedApplication] setStatusBarHidden:false];
    }else{
        [[UIApplication sharedApplication] setStatusBarHidden:true];
    }
}

-(NSString*)appStoreVersion:(NSString*)appleID{
    NSString *appId = appleID;
    if (appId == nil) {
        appId = [[NSBundle mainBundle].infoDictionary objectForKey:@"APPID"];
    }
    NSString *URL = [@"http://itunes.apple.com/cn/lookup?id=" stringByAppendingString: appId];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:URL]];
    [request setHTTPMethod:@"POST"];
    
    NSHTTPURLResponse *urlResponse = nil;
    NSError *error = nil;
    NSData *recervedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
    NSString *results = [[NSString alloc] initWithBytes:[recervedData bytes] length:[recervedData length] encoding:NSUTF8StringEncoding];
    
    NSDictionary *dic = [WXUtility objectFromJSON:results];
    NSArray *infoArray = [dic objectForKey:@"results"];
    NSString*latestVer =@"";
    if ([infoArray count]) {
        NSDictionary *releaseInfo = [infoArray objectAtIndex:0];
        latestVer = [releaseInfo objectForKey:@"version"];
    }
    return latestVer;
}

-(NSString*)bundleVersion{
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    return [infoDic objectForKey:@"CFBundleShortVersionString"];
}

-(NSString*)bundleId{
    return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
}

-(NSString*)deviceId{
    return [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
}

- (void) openAppSetting{
    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    if ([[UIApplication sharedApplication] canOpenURL:url]){
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
        } else {
            [[UIApplication sharedApplication] openURL:url];
        }
    }
}
-(void)openAppOSSetting{
    [self openAppSetting];
}

- (void)openNotifications{
    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    if ([[UIApplication sharedApplication] canOpenURL:url]){
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
        } else {
            [[UIApplication sharedApplication] openURL:url];
        }
    }
}

- (int)notificationSettingTypes{
    __block int types = 0;
    dispatch_sync(dispatch_get_main_queue(), ^{
        if ([[UIDevice currentDevice].systemVersion floatValue]>=8.0f) {
            UIUserNotificationSettings *setting = [[UIApplication sharedApplication] currentUserNotificationSettings];
            types = setting.types;
        }
    });
    return types;
}

-(NSString *)copyPasteboard:(NSString *)value{
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = value;
    return pasteboard.string;
}

-(NSString *)JWTCode:(NSDictionary *)info{
    NSString *type = @"HS256";//加密方式（默认:HS256）
    if (info[@"type"]) {
        type = info[@"type"];
    }
    NSString *secret = info[@"secret"];//服务器机密key
    NSInteger time = [info[@"timeStamp"] integerValue];//间隔时间（秒）
    NSDictionary *payload = info[@"payload"];//加密的信息
    if (time>0) {
        NSString *startStamp = [self dateConversionTimeStamp:[NSDate date]];//有效期开始时间
        NSDate *date = [[NSDate date] dateByAddingTimeInterval:time];
        NSString *endStamp = [self dateConversionTimeStamp:date];//有效期结束时间
        [payload setValue:startStamp forKey:@"iat"];
        [payload setValue:endStamp forKey:@"exp"];
    }
    id<JWTAlgorithm> algorithm = [JWTAlgorithmFactory algorithmByName:type];
    NSString * jwt = [JWTBuilder encodePayload:payload].secret(secret).algorithm(algorithm).encode;
    return jwt;
}

//时间戳转字符串
-(NSString *)timeStampConversionNSString:(NSString *)timeStamp
{
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[timeStamp longLongValue]];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateStr = [formatter stringFromDate:date];
    return dateStr;
}
//时间转时间戳
-(NSString *)dateConversionTimeStamp:(NSDate *)date
{
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[date timeIntervalSince1970]];
    return timeSp;
}

- (void)openRatingReview{
    dispatch_sync(dispatch_get_main_queue(), ^{
        NSString *appId = [[NSBundle mainBundle].infoDictionary objectForKey:@"APPID"];
        NSString *appStoreReviewStr = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/app/id%@?action=write-review", appId];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:appStoreReviewStr]];
    });
}

- (void)openEmail:(NSString*)addr{
    NSString *emailRegex = @"^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(.[a-zA-Z0-9-]+)*.[a-zA-Z0-9]{2,6}$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    if ([emailTest evaluateWithObject:addr]) {
        [self openURL:[NSString stringWithFormat:@"mailto://%@",addr]];
    }else{
        dispatch_async(dispatch_get_main_queue(), ^{
            showAlert(@"提示",@"你的邮箱地址不正确");
        });
    }
}

//打开ＱＱ临时对话框
- (void)openWPA:(NSString*)QQ
{
//    if (QQ && QQ.length >0) {
//        QQApiWPAObject *wpaObj = [QQApiWPAObject objectWithUin:QQ];
//        SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:wpaObj];
//        [QQApiInterface sendReq:req];
//    }
}

- (void)openQQ:(NSString*)QQ{
//    if ([QQApiInterface isQQInstalled]) {
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [self openWPA:qqId];
//        });
//    }else{
//        dispatch_async(dispatch_get_main_queue(), ^{
//            showAlert(@"提示",@"你的移动设备未安装QQ");
//        });
//    }
    //是否安装QQ
    if([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"mqq://"]]){
      //用来接收临时消息的客服QQ号码(注意此QQ号需开通QQ推广功能,不然陌生人向他发送消息会失败)
      NSString *url = [NSString stringWithFormat:@"mqq://im/chat?chat_type=wpa&uin=%@&version=1&src_type=web",QQ];
      [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            showAlert(@"提示",@"你的移动设备未安装QQ");
        });
    }
}


void showAlert(NSString* title, NSString* msg)
{
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:title message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}

#pragma mark - 音视频播放模式
- (BOOL)setAudioPlayMode:(NSString *)mode {
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    NSError *sessionError;
    if ([@"ambient" isEqual:mode]) {
        // 锁屏、APP切入后台或按“静音”时静音，支持与其他 APP 混音，不支持录音，支持播放
        if (@available(iOS 10.0, *)) {
            if (@available(iOS 14.5, *)) {
                [audioSession setCategory:AVAudioSessionCategoryAmbient withOptions:AVAudioSessionCategoryOptionMixWithOthers|AVAudioSessionCategoryOptionDefaultToSpeaker|AVAudioSessionCategoryOptionDuckOthers|AVAudioSessionCategoryOptionAllowBluetoothA2DP|AVAudioSessionCategoryOptionOverrideMutedMicrophoneInterruption
                                    error:nil];
            } else {
                [audioSession setCategory:AVAudioSessionCategoryAmbient withOptions:AVAudioSessionCategoryOptionMixWithOthers|AVAudioSessionCategoryOptionDefaultToSpeaker|AVAudioSessionCategoryOptionDuckOthers|AVAudioSessionCategoryOptionAllowBluetoothA2DP error:nil];
            }
        } else {
            [audioSession setCategory:AVAudioSessionCategoryAmbient withOptions:AVAudioSessionCategoryOptionMixWithOthers|AVAudioSessionCategoryOptionDefaultToSpeaker|AVAudioSessionCategoryOptionDuckOthers error:nil];
        }
    } else if ([@"soloAmbient" isEqual:mode]) {
        // 锁屏、APP切入后台或按“静音”时静音，中断其他 APP 的声音，不支持录音，支持播放
        if (@available(iOS 10.0, *)) {
            if (@available(iOS 14.5, *)) {
                [audioSession setCategory:AVAudioSessionCategorySoloAmbient withOptions:AVAudioSessionCategoryOptionMixWithOthers|AVAudioSessionCategoryOptionDefaultToSpeaker|AVAudioSessionCategoryOptionDuckOthers|AVAudioSessionCategoryOptionAllowBluetoothA2DP|AVAudioSessionCategoryOptionOverrideMutedMicrophoneInterruption
                                    error:nil];
            } else {
                [audioSession setCategory:AVAudioSessionCategorySoloAmbient withOptions:AVAudioSessionCategoryOptionMixWithOthers|AVAudioSessionCategoryOptionDefaultToSpeaker|AVAudioSessionCategoryOptionDuckOthers|AVAudioSessionCategoryOptionAllowBluetoothA2DP error:nil];
            }
        } else {
            [audioSession setCategory:AVAudioSessionCategorySoloAmbient withOptions:AVAudioSessionCategoryOptionMixWithOthers|AVAudioSessionCategoryOptionDefaultToSpeaker|AVAudioSessionCategoryOptionDuckOthers error:nil];
        }
    } else if ([@"playback" isEqual:mode]) {
        // 锁屏、APP切入后台或按“静音”时不静音，默认中断其他 APP 的声音，不支持录音，支持播放
        if (@available(iOS 10.0, *)) {
            if (@available(iOS 14.5, *)) {
                [audioSession setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers|AVAudioSessionCategoryOptionDefaultToSpeaker|AVAudioSessionCategoryOptionDuckOthers|AVAudioSessionCategoryOptionAllowBluetoothA2DP|AVAudioSessionCategoryOptionOverrideMutedMicrophoneInterruption
                                    error:nil];
            } else {
                [audioSession setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers|AVAudioSessionCategoryOptionDefaultToSpeaker|AVAudioSessionCategoryOptionDuckOthers|AVAudioSessionCategoryOptionAllowBluetoothA2DP error:nil];
            }
        } else {
            [audioSession setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers|AVAudioSessionCategoryOptionDefaultToSpeaker|AVAudioSessionCategoryOptionDuckOthers error:nil];
        }
    } else if ([@"record" isEqual:mode]) {
        // APP 静音，中断其他 APP 的声音，支持录音，不支持播放
        if (@available(iOS 10.0, *)) {
            if (@available(iOS 14.5, *)) {
                [audioSession setCategory:AVAudioSessionCategoryRecord withOptions:AVAudioSessionCategoryOptionMixWithOthers|AVAudioSessionCategoryOptionDefaultToSpeaker|AVAudioSessionCategoryOptionDuckOthers|AVAudioSessionCategoryOptionAllowBluetoothA2DP|AVAudioSessionCategoryOptionOverrideMutedMicrophoneInterruption
                                    error:nil];
            } else {
                [audioSession setCategory:AVAudioSessionCategoryRecord withOptions:AVAudioSessionCategoryOptionMixWithOthers|AVAudioSessionCategoryOptionDefaultToSpeaker|AVAudioSessionCategoryOptionDuckOthers|AVAudioSessionCategoryOptionAllowBluetoothA2DP error:nil];
            }
        } else {
            [audioSession setCategory:AVAudioSessionCategoryRecord withOptions:AVAudioSessionCategoryOptionMixWithOthers|AVAudioSessionCategoryOptionDefaultToSpeaker|AVAudioSessionCategoryOptionDuckOthers error:nil];
        }
    } else if ([@"playAndRecord" isEqual:mode]) {
        // 锁屏、APP切入后台或按“静音”时不静音，默认不中断其他 APP 的声音，支持录音和播放
        if (@available(iOS 10.0, *)) {
            if (@available(iOS 14.5, *)) {
                [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionMixWithOthers|AVAudioSessionCategoryOptionDefaultToSpeaker|AVAudioSessionCategoryOptionDuckOthers|AVAudioSessionCategoryOptionAllowBluetoothA2DP|AVAudioSessionCategoryOptionOverrideMutedMicrophoneInterruption
                                    error:nil];
            } else {
                [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionMixWithOthers|AVAudioSessionCategoryOptionDefaultToSpeaker|AVAudioSessionCategoryOptionDuckOthers|AVAudioSessionCategoryOptionAllowBluetoothA2DP error:nil];
            }
        } else {
            [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionMixWithOthers|AVAudioSessionCategoryOptionDefaultToSpeaker|AVAudioSessionCategoryOptionDuckOthers error:nil];
        }
    } else if ([@"audioProcessing" isEqual:mode]) {
        // APP 静音，中断其他 APP 的声音
        if (@available(iOS 10.0, *)) {
            if (@available(iOS 14.5, *)) {
                [audioSession setCategory:AVAudioSessionCategoryAudioProcessing withOptions:AVAudioSessionCategoryOptionMixWithOthers|AVAudioSessionCategoryOptionDefaultToSpeaker|AVAudioSessionCategoryOptionDuckOthers|AVAudioSessionCategoryOptionAllowBluetoothA2DP|AVAudioSessionCategoryOptionOverrideMutedMicrophoneInterruption
                                    error:nil];
            } else {
                [audioSession setCategory:AVAudioSessionCategoryAudioProcessing withOptions:AVAudioSessionCategoryOptionMixWithOthers|AVAudioSessionCategoryOptionDefaultToSpeaker|AVAudioSessionCategoryOptionDuckOthers|AVAudioSessionCategoryOptionAllowBluetoothA2DP error:nil];
            }
        } else {
            [audioSession setCategory:AVAudioSessionCategoryAudioProcessing withOptions:AVAudioSessionCategoryOptionMixWithOthers|AVAudioSessionCategoryOptionDefaultToSpeaker|AVAudioSessionCategoryOptionDuckOthers error:nil];
        }
    } else if ([@"multiRoute" isEqual:mode]) {
        // 锁屏、APP切入后台或按“静音”时不静音，不中断其他 APP 的声音，支持录音和播放
        if (@available(iOS 10.0, *)) {
            if (@available(iOS 14.5, *)) {
                [audioSession setCategory:AVAudioSessionCategoryMultiRoute withOptions:AVAudioSessionCategoryOptionMixWithOthers|AVAudioSessionCategoryOptionDefaultToSpeaker|AVAudioSessionCategoryOptionDuckOthers|AVAudioSessionCategoryOptionAllowBluetoothA2DP|AVAudioSessionCategoryOptionOverrideMutedMicrophoneInterruption
                                    error:nil];
            } else {
                [audioSession setCategory:AVAudioSessionCategoryMultiRoute withOptions:AVAudioSessionCategoryOptionMixWithOthers|AVAudioSessionCategoryOptionDefaultToSpeaker|AVAudioSessionCategoryOptionDuckOthers|AVAudioSessionCategoryOptionAllowBluetoothA2DP error:nil];
            }
        } else {
            [audioSession setCategory:AVAudioSessionCategoryMultiRoute withOptions:AVAudioSessionCategoryOptionMixWithOthers|AVAudioSessionCategoryOptionDefaultToSpeaker|AVAudioSessionCategoryOptionDuckOthers error:nil];
        }
    }

    BOOL result = [audioSession setActive:YES error:&sessionError];
    return result;
}


#pragma mark - 导航方法
- (void)openMap:(NSString*)coordinate title:(NSString*)name{
    NSArray*coordinate2D = [coordinate componentsSeparatedByString:@","];
    if (coordinate2D.count == 2) {
        double latitude  = [(NSString*)coordinate2D[0] doubleValue];
        double longitude = [(NSString*)coordinate2D[1] doubleValue];
        CLLocationCoordinate2D coords = CLLocationCoordinate2DMake(latitude,longitude);
        dispatch_async(dispatch_get_main_queue(), ^{
            [self naviAction:coords];
        });
    }
}

- (NSArray *)getInstalledMapAppWithEndLocation:(CLLocationCoordinate2D)endLocation
{
    NSMutableArray *maps = [NSMutableArray array];
    
    //百度地图
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://"]]) {
        NSMutableDictionary *baiduMapDic = [NSMutableDictionary dictionary];
        baiduMapDic[@"title"] = @"百度地图";
        NSString *urlString = [[NSString stringWithFormat:@"baidumap://map/direction?origin={{我的位置}}&destination=latlng:%f,%f|name=皇御&mode=driving&coord_type=wgs84",endLocation.latitude,endLocation.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        baiduMapDic[@"url"] = urlString;
        [maps addObject:baiduMapDic];
    }
    
    NSString*scheme = @"store";
    NSArray* urlTypes= [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleURLTypes"];
    // 取出 CFBundleURLTypes 对应的 对象(数组)
    // 遍历数组内容
    for (NSDictionary *dict in urlTypes) {
        // 取出子对象中 key CFBundleURLSchemes 对应的 的 字典对象(还是个数组)
        // 具体的数据类型在info.plist 配置文件中可以看出，然后逐类型取出即可找到自己想要拿到那个 值
        NSArray *schemes = dict[@"CFBundleURLSchemes"];
        scheme = schemes[0];
        break;
    }
    
    NSString* appName = [WXAppConfiguration appName];
    
    //高德地图
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]) {
        NSMutableDictionary *gaodeMapDic = [NSMutableDictionary dictionary];
        gaodeMapDic[@"title"] = @"高德地图";
        NSString *urlString = [[NSString stringWithFormat:@"iosamap://navi?sourceApplication=%@&backScheme=%@&lat=%f&lon=%f&dev=1",appName,scheme,endLocation.latitude,endLocation.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        gaodeMapDic[@"url"] = urlString;
        [maps addObject:gaodeMapDic];
    }
    
    //谷歌地图
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"comgooglemaps://"]]) {
        NSMutableDictionary *googleMapDic = [NSMutableDictionary dictionary];
        googleMapDic[@"title"] = @"谷歌地图";
        //        NSString *urlString = [[NSString stringWithFormat:@"comgooglemaps://?x-source=%@&x-success=%@&daddr=%f,%f&directionsmode=driving",@"铸博会",@"bibgold",endLocation.latitude, endLocation.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSString *urlString = [[NSString stringWithFormat:@"comgooglemaps://?saddr=&daddr=%f,%f&directionsmode=driving",endLocation.latitude, endLocation.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        googleMapDic[@"url"] = urlString;
        [maps addObject:googleMapDic];
    }
    
    //苹果地图
    //    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"http://maps.apple.com/"]]) {
    //        NSMutableDictionary *appleMapDic = [NSMutableDictionary dictionary];
    //        appleMapDic[@"title"] = @"苹果地图";
    //        NSString *urlString = [[NSString stringWithFormat:@"http://maps.apple.com/?saddr=&daddr=%f,%f",endLocation.latitude, endLocation.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //        appleMapDic[@"url"] = urlString;
    //        [maps addObject:appleMapDic];
    //    }
    
    return maps;
}

-(void)naviAction:(CLLocationCoordinate2D)coordinate{
    
    NSArray*maps = [self getInstalledMapAppWithEndLocation:coordinate];
    
    UIAlertController* alertController = [UIAlertController alertControllerWithTitle:@"请选择地图"
                                                                             message:nil
                                                                      preferredStyle:UIAlertControllerStyleActionSheet];
    
    for (NSMutableDictionary*dic in maps) {
        UIAlertAction* action = [UIAlertAction actionWithTitle:dic[@"title"] style:UIAlertActionStyleDefault
                                                       handler:^(UIAlertAction * action) {
                                                           [[UIApplication sharedApplication] openURL:[NSURL URLWithString:dic[@"url"]]];
                                                       }];
        [alertController addAction:action];
    }
    
    //自带地图
    [alertController addAction:[UIAlertAction actionWithTitle:@"苹果地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //使用自带地图导航
        MKMapItem *currentLocation =[MKMapItem mapItemForCurrentLocation];
        MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:coordinate addressDictionary:nil]];
//        toLocation.name = @"香港佐敦庇利金街8号百利金商业中心 25楼";
        [MKMapItem openMapsWithItems:@[currentLocation,toLocation] launchOptions:@{MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving,
                                                                                   MKLaunchOptionsShowsTrafficKey:[NSNumber numberWithBool:YES]}];
    }]];
    
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault
                                                         handler:^(UIAlertAction * action) {}];
    [alertController addAction:cancelAction];
    
    UIPopoverPresentationController *popPresenter = [alertController popoverPresentationController];
    if (popPresenter) {
        popPresenter.sourceView = self.weexInstance.viewController.view; // 这就是挂靠的对象
        popPresenter.permittedArrowDirections = UIPopoverArrowDirectionDown;
        popPresenter.sourceRect = CGRectMake(384, 900, 0, 0);
    }
    [self.weexInstance.viewController presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - 检查相机权限
- (void)getCameraPermission:(WXCallback)callback {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    BOOL isCheck = false;
    // 0: 表明用户尚未选择关于客户端是否可以访问硬件
    if (authStatus == AVAuthorizationStatusNotDetermined) {
        isCheck = false;
    }
    // 1: 客户端未被授权访问硬件的媒体类型。用户不能改变客户机的状态,可能由于活跃的限制,如家长控制
    if (authStatus == AVAuthorizationStatusRestricted) {
        isCheck = false;
    }
    // 2: 明确拒绝用户访问硬件支持的媒体类型的客户
    if (authStatus == AVAuthorizationStatusDenied) {
        isCheck = false;
    }
    // 3: 客户端授权访问硬件支持的媒体类型
    if (authStatus == AVAuthorizationStatusAuthorized) {
        isCheck = true;
    }
    if (callback) {
        NSDictionary *dic = @{@"result":@(isCheck), @"status":@(authStatus)};
        callback(dic);
    }
}

- (void)isCheckCameraPermission:(WXCallback)callback {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    BOOL isCheck = false;
    // 表明用户尚未选择关于客户端是否可以访问硬件
    if (authStatus == AVAuthorizationStatusNotDetermined) {
        isCheck = false;
    }
    // 客户端未被授权访问硬件的媒体类型。用户不能改变客户机的状态,可能由于活跃的限制,如家长控制
    if (authStatus == AVAuthorizationStatusRestricted) {
        isCheck = false;
    }
    // 明确拒绝用户访问硬件支持的媒体类型的客户
    if (authStatus == AVAuthorizationStatusDenied) {
        isCheck = false;
    }
    // 客户端授权访问硬件支持的媒体类型
    if (authStatus == AVAuthorizationStatusAuthorized) {
        isCheck = true;
    }
    if (callback) {
        callback(@(isCheck));
    }
}

@end
